/*
 * Copyright (C) Francisco Morero Peyrona. All rights reserved.
 *
 * This software is published under the terms of Open Source
 * License version 1.1, a copy of which has been included with this
 * distribution in the License.txt file.
 */

package jdbcmanager.dbtools.tableditor;

import jdbcmanager.app.*;
import jdbcmanager.swing.table.*;

/**
 * Table parent for the other JxTableXXX in this package.
 * <p>
 * I know that the name is not very appropriate, but...
 *  
 * @author Francisco Morero Peyrona
 */
abstract class JxTableParent extends JxTableVector
{
   JxTableParent()
   {
      setEditable( true );
   }
      
   protected abstract Object createEmptyRow();
   
   //-------------------------------------------------------------------------//
   
   void addRow()
   {
      int nRow = getSelectedRow();
          nRow = Math.max( nRow, 0 );

      ((ParentTableModel) getModel()).addRow( nRow, createEmptyRow() );
      
      setRowSelectionInterval( this.vData.size() - 1, this.vData.size() - 1 );
   }

   void delRow()
   {
      int nRow = getSelectedRow();

      if( nRow > -1 )
      {
         ((ParentTableModel) getModel()).removeRow( nRow );

         if( this.vData.size() > 0 )
         {
            nRow = (nRow == 0 ? 0 : nRow - 1);
            setRowSelectionInterval( nRow, nRow );
         }
      }
      else
      {
         App.showMessage( "There is no selected row." );
      }
   }

   void shiftUpRow()
   {
      int nRow = getSelectedRow();

      if( nRow > 0 )
      {
         ((ParentTableModel) getModel()).moveRow( nRow, -1 );
         setRowSelectionInterval( nRow-1, nRow-1 );
      }
   }

   void shiftDownRow()
   {
      int nRow = getSelectedRow();

      if( nRow > -1 && nRow < this.vData.size() - 1 )
      {
         ((ParentTableModel) getModel()).moveRow( nRow, 1 );
         setRowSelectionInterval( nRow+1, nRow+1 );
      }
   }
   
   //---------------------------------------------------------------//
   // INNER CLASS: TABLE MODEL
   //---------------------------------------------------------------//
   protected abstract class ParentTableModel extends JxTableVector.TableVectorModel
   {
      public void addRow( int nRow, Object oRow )
      {
         JxTableParent.this.vData.insertElementAt( oRow, nRow );
         fireTableRowsInserted( nRow, nRow );
      }

      public void removeRow( int nRow )
      {
         JxTableParent.this.vData.removeElementAt( nRow );
         fireTableRowsDeleted( nRow, nRow );
      }

      public void moveRow( int nRow, int nDirection )
      {
         Object obj = JxTableParent.this.vData.remove( nRow );

         JxTableParent.this.vData.insertElementAt( obj, nRow + nDirection );
      }
   }
}